import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import SpuDetail from '../views/SpuDetail.vue'
import Login from '../views/Login.vue'
import Cart from '../views/Cart.vue'
import Regist from '../views/Regist.vue'
import Account from '../views/Account.vue'
import OrderList from '../views/OrderList.vue'
import SpuList from '../views/SpuList.vue'
import Address from '../views/Address.vue'
import {
  getToken
} from '../utils/local.js'

Vue.use(VueRouter)

const routes = [{
  path: '/',
  name: 'home',
  component: HomeView
}, {
  path: '/spuDetail',
  name: 'SpuDetail',
  component: SpuDetail
}, {
  path: '/customer/cart',
  name: 'Cart',
  component: Cart,
  meta: {
    login: true
  }
}, {
  path: '/login',
  name: 'Login',
  component: Login
}, {
  path: '/regist',
  name: 'Regist',
  component: Regist
}, {
  path: '/account',
  name: 'Account',
  component: Account,
  meta: {
    login: true
  }
}, {
  path: '/customer/orderlist',
  name: 'OrderList',
  component: OrderList,
  meta: {
    login: true
  }
}, {
  path: '/spuList',
  name: 'SpuList',
  component: SpuList
}, {
  path: '/customer/address',
  name: 'Address',
  component: Address
}]

const router = new VueRouter({
  routes,
  mode: 'history'
})

export default router

router.beforeEach((to, from, next) => {
  //判断要访问的路由是否需要登录
  if (to.meta.login) {
    //需要登录
    if (!getToken()) {
      router.push({
        path: '/login'
      })
    } else {
      //已登录,放行
      next()
    }
  } else {
    next()
  }
})
